#include "mcp3021.h"

int TEMP_LOOKUP[] = {-55,-55,-55,-55,-55,-54,-51,-49,-46,-44,-43,-41,-39,-39,-37,-36,-34,-33,-32,-31,-29,-29,-28,-28,-27,-26,-25,-24,-23,-22,-22,-21,-20,-19,-18,-18,-17,-17,-16,-16,-15,-14,-13,-13,-12,-11,-11,-11,-10,-9,-9,-8,-8,-7,-7,-6,-6,-6,-5,-5,-4,-3,-3,-2,-2,-1,0,0,0,0,1,1,2,2,3,3,4,5,5,5,5,6,6,7,7,8,8,9,9,10,10,11,11,11,11,11,12,12,13,13,14,14,15,15,16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,22,22,22,23,23,24,24,25,25,26,26,27,27,27,27,28,29,29,30,30,31,31,32,32,33,33,33,33,34,34,35,35,36,36,37,37,38,38,38,39,39,40,41,41,42,42,43,44,44,44,44,45,46,46,47,48,48,49,50,50,50,50,51,52,52,53,54,54,55,55,56,57,57,58,59,60,61,61,61,62,63,64,65,66,66,67,68,69,70,71,72,72,73,74,76,77,77,78,79,81,82,83,84,86,87,88,89,91,93,94,96,98,99,101,104,105,107,109,112,116,119,121,124,127,132,138,143,148,153,153,153,153,153,153,153,153};

void get_temp(int *temp, TWI_Master_t *temp_sensor){
	int i;
	uint8_t buffer[2];
	if(temp_sensor->status == TWIM_STATUS_READY){
		TWI_MasterRead(temp_sensor, ADDRESS, 2);
		//while(temp_sensor->status != TWIM_STATUS_READY);
	}
	for(i = 0; i < 2; i ++){
		buffer[i] = temp_sensor->readData[i];
	}
	*temp = ((buffer[0] << 6) | (buffer[1] >> 2)) >> 2;
	*temp = TEMP_LOOKUP[*temp];

}
void start_temp_read(TWI_Master_t *temp_sensor){
	if(temp_sensor->status == TWIM_STATUS_READY){
		TWI_MasterRead(temp_sensor, ADDRESS, 2);
	}
}
void finish_temp_read(int *temp, TWI_Master_t *temp_sensor){
	int i;
	char buffer[2];
	while(temp_sensor->status != TWIM_STATUS_READY);
	for(i = 0; i < 2; i ++){
		buffer[i] = temp_sensor->readData[i];
	}
	*temp = ((buffer[0] << 6) | (buffer[1] >> 2)) >> 2;
	*temp = TEMP_LOOKUP[*temp];
}	
